'''
Created on Aug 22, 2010

@author: alia
'''
if __name__ == "__main__":
    import sys,os
    sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
    sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../..'))

import yaml

from filedef import Level, NPC
from data import load_file
__all__ = ['BuildLookupTable', 'GetLookupTable', 'SaveLookupTable', 'SortByTile', 'SortByName', 'SetLookupTable']

class ObjectLookupTable(yaml.YAMLObject):
    yaml_tag = u'!LookupTable'
    def __init__(self, name, mobs):
        self.name = name
        self.mobs = mobs



lookuptable = {}

def SortByTile(yamlDoc):
    manifest = { }
    for data in yamlDoc:
        manifest[data.idx] = data
    return manifest
    
def SortByName(yamlDoc):
    manifest = { }
    for data in yamlDoc:
        manifest[data.name] = data
    return manifest
    
def BuildLookupTable(tablename, filename, f = None):
    if f is None:
        f = load_file(filename)
    d = f.read()
    f.close()
    
    global lookuptable
    
    if lookuptable.get(tablename, None) is None:
        lookuptable[tablename] = yaml.load(d)
    else:
        lookuptable[tablename] += yaml.load(d)
        
    return lookuptable[tablename]
    
def SaveLookupTable(table, filename):
    d = yaml.dump(table)
    f = load_file(filename, "w")
    f.write(d)
    f.close

def GetLookupTable(name):
    if lookuptable.__contains__(name):
        return lookuptable[name]
    return None

def SetLookupTable(name, table):
    lookuptable[name] = table



if __name__ == "__main__":
    loaded = BuildLookupTable("mobs", "../mob/mobs/test.yaml")
    
    print "Loaded mobs:"
    print yaml.dump(mobs_loaded)
    
    mobs += mobs_loaded[:]
    
    print "Saving mobs:"
    SaveLookupTable(mobs, "../mob/mobs/test_out.yaml")
    
    sorted = SortByName(mobs)
    print "Sorted mobs:"
    print yaml.dump(sorted)
    